package com.inspection.job;

import com.inspection.model.Host;
import com.inspection.model.HostInfo;
import com.inspection.model.HostStatus;
import com.inspection.operator.XmlAnalysis;
import com.inspection.utils.AppConfig;
import com.inspection.utils.Tools;
import com.sun.imageio.plugins.png.PNGImageWriter;
import net.sf.ehcache.Element;
import org.jrobin.core.*;
import org.jrobin.graph.RrdGraph;
import org.jrobin.graph.RrdGraphDef;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import sun.java2d.pipe.SpanShapeRenderer;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.ResultSet;
import java.util.*;
import java.util.List;

/**
 * Created by zhujun on 2015-6-9.
 */
public class HostRequestJob implements Job {

    /**
     * @param jobExecutionContext
     * @throws org.quartz.JobExecutionException
     */
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();

        Host host = (Host) jobDataMap.get("value");
        HostInfo hostInfo = XmlAnalysis.getHostInfo(host.getIp(), host.getPort());

        HostStatus hostStatus = new HostStatus();
        hostStatus.setHost(host);
        hostStatus.setHostInfo(hostInfo);

        HashMap cache_hosts = null;
        if(AppConfig.cache.get("hoststatus")==null){
            cache_hosts = new HashMap();
        }else{
            cache_hosts = (HashMap)AppConfig.cache.get("hoststatus").getValue();
        }
        cache_hosts.put(jobDataMap.get("key"), hostStatus);
        Element element = new Element("hoststatus",cache_hosts);
        AppConfig.cache.put(element);
    }


    /**
     * 内存使用情况
     * <p/>
     * 内容包括：总内存，使用内存
     *
     * @param hostInfo
     * @param hostfolder
     */
    public void generate_Mem_used(HostInfo hostInfo, String hostfolder) throws Exception {
        Calendar calendar = Calendar.getInstance();

        long END = Util.getTimestamp(calendar.get(calendar.YEAR), calendar.get(calendar.MONTH) + 1, calendar.get(calendar.DAY_OF_MONTH));    //年、月、日	.解析时间

        calendar.add(Calendar.DAY_OF_MONTH, -1);
        long START = Util.getTimestamp(calendar.get(calendar.YEAR), calendar.get(calendar.MONTH) + 1, calendar.get(calendar.DAY_OF_MONTH));

        String filepath = hostfolder + "/mem_used.rrd";

        RrdDef rrdDef = null;
        rrdDef = new RrdDef(filepath);
//        rrdDef.setStep(1l);
        rrdDef.addDatasource(new DsDef("used", "GAUGE", 300, Double.NaN, Double.NaN));



        /*File file = new File(filepath);

        if(file.exists()){
            file.setReadable(false);
            if(file.canRead()){
                rrdDef = new RrdDef(filepath);
                rrdDef.addDatasource(new DsDef("used", "GAUGE", 1, 0, Double.NaN));
            }
        }else{
            rrdDef = new RrdDef(filepath,START-1,300);
            rrdDef.addDatasource(new DsDef("used", "GAUGE", 1, 0, Double.NaN));
        }*/

        rrdDef.addArchive("AVERAGE", 0.5, 1, 4000);
        rrdDef.addArchive("AVERAGE", 0.5, 6, 4000);
        rrdDef.addArchive("AVERAGE", 0.5, 24, 4000);
        rrdDef.addArchive("AVERAGE", 0.5, 288, 4000);

        rrdDef.addArchive("MAX", 0.5, 1, 4000);
        rrdDef.addArchive("MAX", 0.5, 6, 4000);
        rrdDef.addArchive("MAX", 0.5, 24, 4000);
        rrdDef.addArchive("MAX", 0.5, 288, 4000);

        rrdDef.addArchive("MIN", 0.5, 1, 4000);
        rrdDef.addArchive("MIN", 0.5, 6, 4000);
        rrdDef.addArchive("MIN", 0.5, 24, 4000);
        rrdDef.addArchive("MIN", 0.5, 288, 4000);

        rrdDef.addArchive("LAST", 0.5, 1, 4000);
        rrdDef.addArchive("LAST", 0.5, 6, 4000);
        rrdDef.addArchive("LAST", 0.5, 24, 4000);
        rrdDef.addArchive("LAST", 0.5, 288, 4000);

        createFileAndPNG(rrdDef, START, END, filepath, hostfolder);


    }

    public void createFileAndPNG(RrdDef rrdDef, Long START, Long END, String filepath, String hostfolder) throws RrdException, IOException {
        RrdDb rrdDb = new RrdDb(rrdDef);

        Sample simple = rrdDb.createSample();
        Long last = 0l;
        for (int i = 0; i < 1000; i++) {
            last = Util.getTimestamp(new Date()) + i * 300;
            simple.setTime(last);
            simple.setValue("used", new Random(1000).nextDouble());
        }

        simple.update();

        rrdDb.close();

        RrdGraphDef graphDef = new RrdGraphDef();
        graphDef.setTimePeriod(Util.getTimestamp(new Date()) - 3000, last);

        graphDef.setDefaultFont(new Font(Font.MONOSPACED, Font.PLAIN, 10));

        graphDef.datasource("used", filepath, "used", "AVERAGE");
        graphDef.datasource("a", filepath, "used", "MAX");
        graphDef.datasource("b", filepath, "used", "MIN");
        graphDef.area("used", Color.orange, "使用内存");
        graphDef.area("a", Color.orange, "a");
        graphDef.area("b", Color.orange, "b");
        graphDef.setShowSignature(false);

        graphDef.setBackColor(new Color(255, 255, 255));

        RrdGraph rrdGraph = new RrdGraph(graphDef);
        rrdGraph.saveAsPNG(hostfolder + "/mem_used.png", 400, 400);
    }


//    public void generate_png(Long start,Long end) throws Exception{
//        RrdGraphDef graphDef = new RrdGraphDef(start, end);
//        graphDef.datasource("Used", "F:\\temp\\inspection\\127.0.0.1\\mem_used.rrd", "Used", "AVERAGE");
//        graphDef.line("Used", new Color(0xFF, 0, 0), null, 1);
//
////        graphDef.stack("Used", new Color(0xFF, 0xFF, 0), "input 2@r");
////        graphDef.setCanvasColor(new Color(174, 247, 255));
//        graphDef.gprint("Used", "AVERAGE", "avg=@2 @sbits/sec");
//        graphDef.setShowSignature(false);
//        RrdGraph rrdGraph = new RrdGraph(graphDef);
//        rrdGraph.saveAsPNG("d:\\test1.png", 400, 100);
//    }
//
//
//
//    public static void main(String[] args){
//
//        HostInfo hostInfo = XmlAnalysis.getHostInfo("127.0.0.1",8821);
//
//        String hostfolder = "F:\\temp\\inspection/127.0.0.1";
//        File file = new File(hostfolder);
//        if(!file.exists()){
//            file.mkdir();
//        }
//
//        //获取到基本数据后，进行RRD数据的写入。
//        try {
//            //数据基本序列化
//            ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(hostfolder+"/info.dat"));
//            os.writeObject(hostInfo);
//            os.close();
//
//            HostRequestJob hrj = new HostRequestJob();
//
//            String filePath = hostfolder + "/mem_used.rrd";
//            hrj.generate_Mem_used(hostInfo, filePath);
//            Long lasttime = Tools.getLastUnix();
//            RrdGraphDef graphDef = new RrdGraphDef(lasttime-3600,lasttime);
//            graphDef.datasource("Used", filePath, "Used", "AVERAGE");
//            graphDef.line("Used", new Color(0xFF, 0, 0), null, 1);
//            graphDef.setShowSignature(false);
//            RrdGraph rrdGraph = new RrdGraph(graphDef);
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

}
